/**
 * 消除异步传染性
 */
// async function getUser() {
//   return await fetch('./1.json')
// }

// async function m1() {
//   const user = await getUser()
//   // other workers
//   return user
// }

// async function m2() {
//   const user = await m1()
//   // other workers
//   return user
// }

// async function m3() {
//   const user = await m2()
//   // other workers
//   return user
// }

// async function main() {
//   const user = await m3()
//   console.log(user);
// }

function getUser() {
  return fetch('./1.json')
}

function m1() {
  const user = getUser()
  // other workers
  return user
}

function m2() {
  const user = m1()
  // other workers
  return user
}

function m3() {
  const user = m2()
  // other workers
  return user
}

function main() {
  console.log('main begin');
  const user = m3()
  console.log(user);
}

function run(func) {
  // 1. 改动fetch
  const oldFetch = window.fetch
  let cache = {
    status: 'pending',
    value: null
  }
  function newFetch(...args) {
    // 有缓存返回缓存
    if (cache.status === 'fulfilled') {
      return cache.value
    } else if (cache.status === 'rejected') {
      return cache.value
    }
    // 没有缓存
    // 发送请求
    const p = oldFetch(...args)
      .then(data => data.json())
      .then(data => {
        cache.value = data
        cache.status = 'fulfilled'
      })
      .catch(err => {
        cache.value = err
        cache.status = 'rejected'
      })
    // 抛出错误
    throw p
  }
  window.fetch = newFetch
  // 2. 执行func
  try {
    func()
  } catch (error) {
    if (error instanceof Promise) {
      error.finally(() => {
        window.fetch = newFetch
        func()
        window.fetch = oldFetch
      })
    }
  }
  // 3. 改回fetch
  window.fetch = oldFetch
}

run(main)